import * as vscode from 'vscode';
import { Helper } from '../helper';
import { getRelativePath } from '../helper/getRelativePath';
import { log } from '../helper/outputChannel';
import { genApiTsFile } from './genApiTsFile';
import { Const } from '../helper/outputFile';

export async function importApi() {
  const [document, textEditor] = await Helper.activeTsDocument().catch(e => {
    vscode.window.showWarningMessage(e.message);
  }) || [];

  if (!document || !textEditor) { return; }

  let result = await genApiTsFile(undefined);
  if (!result) {
    return;
  }
  let importedFilePath = result.filePath;
  let editFilePath = Helper.fsPath(document.uri);
  if (editFilePath === importedFilePath) {
    return log.warn('this file cannot import itself.');
  }
  let left = 0;
  while (importedFilePath[left] === editFilePath[left]) {
    ++left;
  }
  editFilePath = editFilePath.substring(left).replace(/(.*?)\\/g, '../');
  importedFilePath = importedFilePath.substring(left).replace(/\\/g, '/');
  const importName = importedFilePath.substring(importedFilePath.lastIndexOf('/') + 1).replace(/.ts$/g, '');

  const importPath = getRelativePath(editFilePath, importedFilePath);



  const importSignal = `TAV`;
  const newLine = result.tavValues.howToImport
    .replace(Const.fileName, importName)
    .replace(Const.relativePathWithSuffix, importPath)
    .replace(Const.relativePath, importPath.replace(/.ts$/g, '')) +
    ` ${result.tavValues.lineComment.replace('$$', importSignal)}`;

  let imported = false;
  let insertLine: vscode.TextLine | undefined;
  for (let i = document.lineCount - 1; i >= 0; --i) {
    const line = document.lineAt(i);
    const lineStr = line.text;
    if (lineStr.startsWith('import ') && !insertLine) {
      insertLine = line;
    }
    if (lineStr.startsWith('import ') && lineStr.match('/' + importName)) {
      log.info(`${importName} already imported.`);
      imported = true;
      insertLine = line;
      break;
    }
  }

  const editResult = await textEditor.edit((editBuilder) => {
    if (imported) {
      editBuilder.replace(insertLine!.range, newLine);
    } else if (insertLine) {
      editBuilder.insert(new vscode.Position(insertLine.lineNumber + 1, 0), newLine + '\n');
    } else {
      editBuilder.insert(new vscode.Position(0, 0), newLine + '\n');
    }
  });

  vscode.window.showTextDocument(document);
  if (!editResult) {
    vscode.window.showWarningMessage('文档编辑失败！');
    return;
  }

  return { importName };
}